package com.ikingtech.framework.sdk.approve.callback;

import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.core.support.LogHelper;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Slf4j
@ApiController(value = "/approve/callback", name = "审批中心-审批回调", description = "审批中心-审批回调")
@RequiredArgsConstructor
public class ApproveCallbackResolver {

    private final List<ApproveProcessCallback> callbacks;

    private final Map<String, ApproveProcessCallback> callbackMap = new HashMap<>();

    /**
     * 处理审批回调请求
     * @param param 审批回调参数
     * @return 处理结果
     */
    @PostRequest(order = 1,value = "/resolve", summary = "处理审批回调请求", description = "处理审批回调请求")
    public R<Object> resolve(@RequestBody ApproveCallbackParam param) {
        // 如果参数为空，则返回失败结果
        if (null == param) {
            return R.failed("[APPROVE CALLBACK RESOLVER]审批回调参数为空");
        }
        // 获取对应的审批回调方法
        ApproveProcessCallback callback = this.callbackMap.get(param.getBusinessType());
        // 如果回调方法存在，则执行回调方法
        if (null != callback) {
            LogHelper.info("APPROVE CALLBACK RESOLVER", "触发审批回调[{}]", param);
            callback.invoke(param);
        } else {
            // 如果回调方法不存在，则返回失败结果
            return R.failed("[APPROVE CALLBACK RESOLVER]未找到审批回调方法");
        }
        LogHelper.info("APPROVE CALLBACK RESOLVER", "审批回调执行完成");
        return R.ok();
    }

    public void init() {
        this.callbackMap.putAll(Tools.Coll.convertMap(this.callbacks, ApproveProcessCallback::businessType));
    }
}
